package sqlitedb

import (
	"github.com/gogf/gf/errors/gerror"
	"gitlab.local/DO-module/new-filemanage-module/src/core/sqlitedb/sqlitemodel"
	"gorm.io/gorm"
)

func (d *SqliteDb) DbGet() *gorm.DB {
	return d.Db
}

func (d *SqliteDb) CloseDb() error {
	b, e := d.Db.DB()
	if e != nil {
		return gerror.Wrap(e, "CloseDb")
	}
	return b.Close()
}

// tableMigration 表迁移
func (d *SqliteDb) tableMigration() error {
	_ = d.shareConfig()
	_ = d.sharePath()
	_ = d.appAccessUser()
	_ = d.otpTrust()
	_ = d.autoMigratorColumn()
	_ = d.fileRecently()
	_ = d.addForeignKey()
	_ = d.aclList()
	return nil
}

func (d *SqliteDb) autoMigratorColumn() error {
	if !d.Db.Migrator().HasColumn(&sqlitemodel.Share{}, "time_machine_limit") {
		_ = d.Db.Migrator().AddColumn(&sqlitemodel.Share{}, "time_machine_limit")
	}
	if d.Db.Migrator().HasColumn(&sqlitemodel.Share{}, "uuid") {
		_ = d.Db.Migrator().DropColumn(&sqlitemodel.Share{}, "uuid")
	}
	if !d.Db.Migrator().HasColumn(&sqlitemodel.Share{}, "usb") {
		_ = d.Db.Migrator().AddColumn(&sqlitemodel.Share{}, "usb")
	}
	if !d.Db.Migrator().HasColumn(&sqlitemodel.Share{}, "quota_flag") {
		_ = d.Db.Migrator().AddColumn(&sqlitemodel.Share{}, "quota_flag")
	}
	return d.Db.Table("user_table").Migrator().AutoMigrate(&sqlitemodel.Member{})
}

func (d *SqliteDb) aclList() error {
	if !d.Db.Migrator().HasColumn(&sqlitemodel.AclList{}, "acl_type") {
		_ = d.Db.Migrator().AddColumn(&sqlitemodel.AclList{}, "acl_type")
	}
	return d.Db.Migrator().AutoMigrate(&sqlitemodel.AclList{})
}

// share_config表
func (d *SqliteDb) shareConfig() error {
	if !d.Db.Migrator().HasColumn(&sqlitemodel.ShareConfig{}, "close_status") || !d.Db.Migrator().HasColumn(&sqlitemodel.ShareConfig{}, "share_link") {
		_ = d.Db.Migrator().DropTable(&sqlitemodel.ShareConfig{})
	}
	return d.Db.Migrator().AutoMigrate(&sqlitemodel.ShareConfig{})
}

func (d *SqliteDb) sharePath() error {
	return d.Db.Migrator().AutoMigrate(&sqlitemodel.SharePath{})
}

func (d *SqliteDb) appAccessUser() error {
	return d.Db.Migrator().AutoMigrate(&sqlitemodel.AppAccessUser{})
}

func (d *SqliteDb) otpTrust() error {
	return d.Db.Migrator().AutoMigrate(&sqlitemodel.Trust{})
}

func (d *SqliteDb) fileRecently() error {
	return d.Db.Migrator().AutoMigrate(&sqlitemodel.FileRecently{})
}

func (d *SqliteDb) addForeignKey() error {
	_ = d.Db.Migrator().DropConstraint(&sqlitemodel.ExternalAcl{}, "fk_external_acl_user_table")
	err := d.Db.Migrator().AutoMigrate(&sqlitemodel.ExternalAcl{})
	return err
}
